package com.lanou.moving.fragment;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.moving.R;
import com.lanou.moving.adapter.RadioStationAdapter;
import com.lanou.moving.constant.URL;
import com.lanou.moving.entity.MusicInfo;
import com.lanou.moving.entity.RadioPlayRoot;
import com.lanou.moving.entity.RadioRoot;
import com.lanou.moving.eventBus.MyEventBus;
import com.lanou.moving.volley.GsonRequest;
import com.lanou.moving.volley.StringRequestUtf;
import com.lanou.moving.volley.VolleySingleton;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by dllo on 15/10/24.
 */
public class RadioStationFragment extends BackHandledFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private Context context;
    private VolleySingleton volleySingleton;
    private GsonRequest<RadioRoot> radioRootGsonRequest;
    private ArrayList<RadioRoot.DatasEntity> datasEntityArrayList;
    private ArrayList<RadioRoot.DatasEntity.DataEntity> entityArrayList;
    private ListView radio_listview;
    private RadioStationAdapter radioStationAdapter;

    private RadioButton radiao_hot, radio_recently, radio_scene, radio_years, radio_mood, radio_language, radio_style, radio_characteristic, radio_crowd;
    private ImageView radio_back;
    private View view;

    private ArrayList<RadioPlayRoot.DataEntity> playEntityList;
    private RadioPlayRoot playRoot;
    private String radioDetail_url;
    private ArrayList<String> playUrl;
    private MediaPlayer mediaPlayer;
    private int tag_id;
    private int currIndex = 0;
    private GsonRequest<RadioPlayRoot> playRootGsonRequest;
    private RadioPlayRoot.DataEntity dataEntity;
    private List<RadioPlayRoot.DataEntity> dataEntities;
    private List<MusicInfo> musicInfos;

    @Override
    protected boolean onBackPressed() {
        return false;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.radio_station_fragment, null);
        volleySingleton = VolleySingleton.getInstance(context);
        radio_listview = (ListView) view.findViewById(R.id.radio_listview);
        radio_listview.setOnItemClickListener(this);
        radio_listview.setItemsCanFocus(true);
        radio_listview.setEnabled(true);
        mediaPlayer = new MediaPlayer();
        getRadio();
        initView();
        return view;
    }

    public void initView() {
        //热门
        radiao_hot = (RadioButton) view.findViewById(R.id.radiao_hot);
        radiao_hot.setOnClickListener(this);
        //最近
        radio_recently = (RadioButton) view.findViewById(R.id.radio_recently);
        radio_recently.setOnClickListener(this);
        //场景
        radio_scene = (RadioButton) view.findViewById(R.id.radio_scene);
        radio_scene.setOnClickListener(this);
        //年代
        radio_years = (RadioButton) view.findViewById(R.id.radio_years);
        radio_years.setOnClickListener(this);
        //心情
        radio_mood = (RadioButton) view.findViewById(R.id.radio_mood);
        radio_mood.setOnClickListener(this);
        //语言
        radio_language = (RadioButton) view.findViewById(R.id.radio_language);
        radio_language.setOnClickListener(this);
        //风格
        radio_style = (RadioButton) view.findViewById(R.id.radio_style);
        radio_style.setOnClickListener(this);
        //特色
        radio_characteristic = (RadioButton) view.findViewById(R.id.radio_characteristic);
        radio_characteristic.setOnClickListener(this);
        //人群
        radio_crowd = (RadioButton) view.findViewById(R.id.radio_crowd);
        radio_crowd.setOnClickListener(this);

        //返回
        radio_back = (ImageView) view.findViewById(R.id.radio_back);
        radio_back.setOnClickListener(this);

    }

    public void getRadio() {
        radioRootGsonRequest = new GsonRequest<RadioRoot>(URL.URL_RADIO, RadioRoot.class, new Response.Listener<RadioRoot>() {
            @Override
            public void onResponse(RadioRoot response) {
                datasEntityArrayList = response.getData();
                entityArrayList = datasEntityArrayList.get(0).getData();
                radioStationAdapter = new RadioStationAdapter(context, entityArrayList, mediaPlayer);
                radio_listview.setAdapter(radioStationAdapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(radioRootGsonRequest);
    }

    /**
     * 点击电台快捷分类,显示数据
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.radiao_hot:
                entityArrayList = datasEntityArrayList.get(0).getData();
                break;
            case R.id.radio_recently:
                break;
            case R.id.radio_scene:
                entityArrayList = datasEntityArrayList.get(1).getData();
                break;
            case R.id.radio_years:
                entityArrayList = datasEntityArrayList.get(2).getData();
                break;
            case R.id.radio_mood:
                entityArrayList = datasEntityArrayList.get(3).getData();
                break;
            case R.id.radio_language:
                entityArrayList = datasEntityArrayList.get(4).getData();
                break;
            case R.id.radio_style:
                entityArrayList = datasEntityArrayList.get(5).getData();
                break;
            case R.id.radio_characteristic:
                entityArrayList = datasEntityArrayList.get(6).getData();
                break;
            case R.id.radio_crowd:
                entityArrayList = datasEntityArrayList.get(7).getData();
                break;
            case R.id.radio_back:
                getFragmentManager().popBackStack();
                break;
        }
        radioStationAdapter = new RadioStationAdapter(context, entityArrayList, mediaPlayer);
        radio_listview.setAdapter(radioStationAdapter);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

        RadioRoot.DatasEntity.DataEntity dataEntity = (RadioRoot.DatasEntity.DataEntity) parent.getItemAtPosition(position);
        musicInfos = new ArrayList<>();
        tag_id = dataEntity.getTag_id();
        String url = URL.RADIO_PLAY_START + tag_id + URL.RADIO_PLAY_END;
        StringRequestUtf stringRequestUtf = new StringRequestUtf(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                RadioPlayRoot radioStationPlay = gson.fromJson(response, RadioPlayRoot.class);
                dataEntities = radioStationPlay.getData();
                for (RadioPlayRoot.DataEntity radioEntity : dataEntities) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setUrl(radioEntity.getUrlList().get(0).getUrl());
                    musicInfo.setDuration(radioEntity.getUrlList().get(0).getDuration());
                    musicInfo.setSingerId(radioEntity.getSingerId());
                    musicInfo.setSingerName(radioEntity.getSingerName());
                    musicInfo.setSongId(radioEntity.getSongId());
                    musicInfo.setSongName(radioEntity.getName());
                    musicInfo.setAlbum(radioEntity.getAlbumName());
                    musicInfo.setResouce("网络");
                    musicInfos.add(musicInfo);
                }
                EventBus.getDefault().post(new MyEventBus.Deliver(musicInfos, dataEntities.get(0).getName()));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(stringRequestUtf);
    }

    /**
     * 网络拉取电台播放数据
     */
    private void getPlayInfo(int position) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                radioDetail_url = "http://api.fm.ttpod.com/radio/" + tag_id + "/songs?page_num=1&page_size=5&userid=0";
                playRootGsonRequest = new GsonRequest<>(radioDetail_url, RadioPlayRoot.class, new Response.Listener<RadioPlayRoot>() {
                    @Override
                    public void onResponse(RadioPlayRoot response) {
                        playEntityList = (ArrayList<RadioPlayRoot.DataEntity>) response.getData();
                        playUrl = new ArrayList<>();
                        for (int i = 0; i < playEntityList.size(); i++) {
                            playUrl.add(playEntityList.get(i).getAuditionList().get(0).getUrl());
                        }
                        play();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                volleySingleton.addQueue(playRootGsonRequest);
            }
        }).start();
    }

    /**
     * 电台播放功能
     */
    public void play() {

        if (!mediaPlayer.isPlaying()) {
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(playUrl.get(currIndex));
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                currIndex++;
                if (currIndex < playUrl.size()) {
                    try {
                        mp.reset();
                        mp.setDataSource(playUrl.get(currIndex));
                        mp.prepare();
                        mp.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }
}